package com.zyx.concurrentdemo.c06cas;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

/**
 * @author Yaxi.Zhang
 * @since 2021/10/18 11:27
 * desc: 使用 AtomicReferenceFieldUpdater 对属性进行线程安全的修改
 */
@Slf4j(topic = "c.TestAtomicReferenceFieldUpdater")
public class TestAtomicReferenceFieldUpdater {

    public static void main(String[] args) {
        Student student = new Student();


        AtomicReferenceFieldUpdater<Student, String> updater = AtomicReferenceFieldUpdater.newUpdater(Student.class, String.class, "name");

        student.name = "李四";

        log.debug("更新成功?{}", updater.compareAndSet(student, null, "张三"));
        log.debug("姓名:{}", student.name);
    }
}

class Student {

    volatile String name;

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                '}';
    }
}